package com.tbit.uqbike.config.threadpool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: chen
 * @Description: 线程池配置
 * @Date: 创建于 13:47 2022/7/15
 */
@EnableAsync
@Configuration
public class ThreadPoolConfig {
    /**
     * 最大线程数
     */
    @Value("${thread.maxPoolSize}")
    private Integer maxPoolSize;
    /**
     * 核心线程数
     */
    @Value("${thread.corePoolSize}")
    private Integer corePoolSize;
    /**
     * 队列大小
     */
    @Value("${thread.queueCapacity}")
    private Integer queueCapacity;
    /**
     * 线程活跃时间（秒）
     */
    @Value("${thread.keepAliveSeconds}")
    private Integer keepAliveSeconds;
    /**
     * 默认线程名称
     */
    @Value("${thread.threadNamePrefix}")
    private String threadNamePrefix;
    /**
     * 所有任务结束后再关闭线程池
     */
    @Value("${thread.waitForTasksToCompleteOnShutdown}")
    private Boolean waitForTasksToCompleteOnShutdown;

    @Bean("taskExecutor")
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数等于系统核数--8核
        int availableProcessors = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(availableProcessors);
        // 设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        executor.setCorePoolSize(corePoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        // 设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 线程满了之后由调用者所在的线程来执行
        // 拒绝策略：CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 设置默认线程名称
        executor.setThreadNamePrefix(threadNamePrefix);
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown);
        // 任务的等待时间 如果超过这个时间还没有销毁就 强制销毁，以确保应用最后能够被关闭，而不是阻塞住。
        executor.setAwaitTerminationSeconds(60);
        //执行初始化
        executor.initialize();
        return executor;
    }

    @Bean
    public ThreadPoolExecutor orderTraceExecutor() {
        return new ThreadPoolExecutor(
                5,                      // 核心线程数
                10,                     // 最大线程数
                60L,                    // 空闲线程存活时间
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(100),  // 工作队列
                new ThreadFactoryBuilder()
                        .setNameFormat("order-trace-pool-%d")
                        .build(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

}
